package com.liujit.validator.utils;

import com.liujit.validator.domain.ErrorMessage;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.validation.ConstraintViolation;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @description: 参数无效项处理器
 * @author: liujun
 * @create: 2021/1/4 10:30 上午
 **/
public class ValidHelper {

    public static List<ErrorMessage> convertConstraintViolationSet(Set<ConstraintViolation<?>> cvSet) {
        if (CollectionUtils.isEmpty(cvSet)) {
            return null;
        }
        List<ErrorMessage> parameterInvalidItemList = new ArrayList<>();
        for (ConstraintViolation<?> cv : cvSet) {
            ErrorMessage errorMessage = new ErrorMessage();
            String propertyPath = cv.getPropertyPath().toString();
            if (propertyPath.contains(".")) {
                String[] propertyPathArr = propertyPath.split("\\.");
                errorMessage.setProperty(propertyPathArr[propertyPathArr.length - 1]);
            } else {
                errorMessage.setProperty(propertyPath);
            }
            errorMessage.setMessage(cv.getMessage());
            parameterInvalidItemList.add(errorMessage);
        }
        return parameterInvalidItemList;
    }

    public static List<ErrorMessage> convertBindingResult(BindingResult bindingResult) {
        if (bindingResult == null) {
            return null;
        }
        List<ErrorMessage> parameterInvalidItemList = new ArrayList<>();
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrorList) {
            parameterInvalidItemList.add(new ErrorMessage(fieldError.getField(), fieldError.getDefaultMessage()));
        }
        return parameterInvalidItemList;
    }
}
